<template>
  <a-modal
    :title="fullScreenTitle"
    :visible="visible"
    @ok="handleCancel"
    @cancel="handleCancel"
    :width="width"
    :class="{ myFullScreen: fullScreen }"
  >
    <a-form-model ref="form" :model="form" :rules="validatorRules">
      <a-row>
        <a-col :span="5">法人名称 </a-col>
        <a-col :span="5">用户名称 </a-col>
        <a-col :span="8">主题名称 </a-col>
        <a-col :span="6">操作 </a-col>
      </a-row>
      <a-row>
        <a-col :span="5">
          <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="" prop="bankNoCd">
            <a-select
              show-search
              allow-clear
              v-model="form.bankNoCd"
              style="width: 100%"
              placeholder="请选择法人"
              :disabled="form.hasOwnProperty('id')"
              :getPopupContainer="
                (triggerNode) => {
                  return triggerNode.parentNode || document.body
                }
              "
              @change="selectBankNoCd"
            >
              <a-select-option v-for="item in reportsOptions" :key="item.value" :value="item.value" :label="item.label">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="5">
          <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="" prop="userName">
            <a-select
              show-search
              allow-clear
              v-model="form.userName"
              style="width: 100%"
              placeholder="请选择用户"
              :disabled="form.hasOwnProperty('id')"
              :getPopupContainer="
                (triggerNode) => {
                  return triggerNode.parentNode || document.body
                }
              "
            >
              <a-select-option
                v-for="item in roleList[form.bankNoCd]"
                :key="item.value"
                :value="item.value"
                :label="item.label"
                :disabled="list.some((el) => el.userName === item.value && el.bankNoCd === form.bankNoCd)"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label=""
            prop="themeCode"
            :rules="{
              required: true,
              message: '请选择主题',
              trigger: 'change',
            }"
          >
            <a-select
              show-search
              allow-clear
              v-model="form.themeCode"
              style="width: 100%"
              placeholder="请选择主题"
              :maxTagCount="2"
              mode="multiple"
              :getPopupContainer="
                (triggerNode) => {
                  return triggerNode.parentNode || document.body
                }
              "
            >
              <a-select-option v-for="item in themeList" :key="item.value" :value="item.value" :label="item.label">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="6">
          <a-form-model-item>
            <a-button
              v-show="!(form.hasOwnProperty('id') || form.hasOwnProperty('vId'))"
              icon="plus"
              @click="addDomain"
              type="primary"
              :loading="confirmLoading"
            >
              添加
            </a-button>
            <a-button @click="removeDomain()" v-show="form.hasOwnProperty('id') || form.hasOwnProperty('vId')">
              取消
            </a-button>
            <a-button
              v-show="form.hasOwnProperty('id') || form.hasOwnProperty('vId')"
              :style="{ marginLeft: '8%' }"
              icon="check"
              @click="editDomain"
              type="primary"
              :loading="confirmLoading"
            >
              保存
            </a-button>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-table
        :columns="columns"
        :data-source="list"
        :rowKey="(record) => (record.bankNoCd ? record.bankNoCd + record.userName : record.vId)"
        :pagination="false"
        :loading="confirmLoading"
      >
        <span
          slot="bankNoCd"
          slot-scope="text"
          :title="(text && reportsOptions.length > 0 && filterLabel(text, reportsOptions)) || ''"
        >
          {{ (text && reportsOptions.length > 0 && filterLabel(text, reportsOptions)) || '' }}
        </span>
        <span
          slot="userName"
          slot-scope="text, record"
          :title="
            (text &&
              roleList &&
              roleList[record.bankNoCd] &&
              roleList[record.bankNoCd].length > 0 &&
              filterLabel(text, roleList[record.bankNoCd])) ||
            text
          "
        >
          {{
            (text &&
              roleList &&
              roleList[record.bankNoCd] &&
              roleList[record.bankNoCd].length > 0 &&
              filterLabel(text, roleList[record.bankNoCd])) ||
            text
          }}
        </span>
        <span
          slot="themeCode"
          slot-scope="text"
          :title="(text && themeList.length > 0 && filterRuler(text, themeList)) || ''"
        >
          {{ (themeList.length > 0 && filterRuler(text, themeList)) || '' }}
        </span>
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)" v-has="'reportManage:edit'">编辑</a>
          <a-popconfirm title="确定删除吗?" @confirm="() => removeDomain(record)">
            <a :style="{ marginLeft: '15px' }" v-has="'juridicalPerson:edit'"> 删除 </a>
          </a-popconfirm>
        </span>
      </a-table>
    </a-form-model>
  </a-modal>
</template>

<script>
import FullScreenTitle from '@/components/LIbb/FullScreenTitle'
import {
  queryBankNoCdList,
  queryRoleList,
  queryThemeList,
  addRoleMessage,
  deleteRoleMess,
  queryRoleMessageList,
} from '@/api/api'

const columns = [
  {
    title: '法人名称',
    dataIndex: 'bankNoCd',
    scopedSlots: { customRender: 'bankNoCd' },
    ellipsis: true,
  },
  {
    title: '用户名称',
    dataIndex: 'userName',
    scopedSlots: { customRender: 'userName' },
    ellipsis: true,
  },
  {
    title: '主题名称',
    dataIndex: 'themeCode',
    scopedSlots: { customRender: 'themeCode' },
    ellipsis: true,
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'LlbbJuridicalPersonRuleForm',
  components: { FullScreenTitle },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    visible: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      columns,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 0 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 22 },
      },
      validatorRules: {
        bankNoCd: [{ required: true, message: '请选择法人!' }],
        userName: [{ required: true, message: '请选择用户!' }],
        themeCode: [{ required: true, message: '请选择主题!' }],
      },
      reportsOptions: [],
      form: {
        bankNoCd: '',
        userName: '',
        themeCode: [],
      },
      confirmLoading: false,
      vId: 2,
      rulesList: {},
      roleList: {},
      themeList: [],
      list: [],
      width: 1000,
      fullScreen: false,
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  watch: {
    visible(newValue, oldValue) {
      if (newValue) {
        this.initList()
      }
    },
  },
  created() {
    this.initReportList2()
    // this.initRoleList()
    this.initThemeList()
  },
  methods: {
    fullScreenTitle() {
      return (
        <full-screen-title
          title="打包配置"
          fullCoderEdit={this.fullCoderEdit}
          fullScreen={this.fullScreen}
        ></full-screen-title>
      )
    },
    fullCoderEdit() {
      this.width = this.fullScreen ? 1000 : '100%'
      this.fullScreen = !this.fullScreen
    },
    filterLabel(value, list) {
      if (list.length && value) {
        let data = list.filter((item) => item.value === value)[0]
        return data ? data.label : ''
      }
      return ''
    },
    filterRuler(ids = [], list = []) {
      let names = []
      if (ids) {
        ids.map((item) => {
          if (list && list.some((el) => el.value === item)) {
            let name = list.filter((el) => el.value === item)[0]
            if (name) {
              names.push(name.label)
            }
          }
        })
      }
      return names.length > 0 ? names.join(',') : ''
    },
    initList() {
      queryRoleMessageList().then((res) => {
        if (res.code === 200) {
          let data = res.result || []
          data = data.map((item) => {
            item.themeCode = item && item.themeCode ? item.themeCode.split(',') : []
            if (item.bankNoCd) {
              this.selectBankNoCd(item.bankNoCd)
            }
            return item
          })
          this.list = data
        } else {
          this.$message.warning('服务器出错')
        }
        this.confirmLoading = false
      })
    },
    // 提交
    handleSubmit() {
      this.confirmLoading = true
      this.$refs.form.validate((valid) => {
        if (valid) {
          queryRoleMessageList().then((res) => {
            if (res.code === 200) {
              let data = res.result.records || []
              data = data.map((item) => {
                item.themeCode = item && item.themeCode ? item.themeCode.split(',') : []
                return item
              })
              this.list = data
            } else {
              this.$message.warning('服务器出错')
            }
            this.confirmLoading = false
          })
        } else {
          this.confirmLoading = false
          return false
        }
      })
    },
    handleEdit(record) {
      this.form = JSON.parse(JSON.stringify(record))
    },
    resetForm() {
      this.$refs.form.resetFields()
    },
    editDomain() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.confirmLoading = true
          const themeCode = this.form.themeCode ? this.form.themeCode.join(',') : ''
          addRoleMessage({ ...this.form, themeCode }).then((res) => {
            if (res.code === 200) {
              this.$message.success('修改成功')
              this.initList()
              this.form = {}
              this.resetForm()
            } else {
              this.confirmLoading = false
              this.$message.warning('服务器出错')
            }
          })
        } else {
          return false
        }
      })
    },
    addDomain() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          console.log('%c [ valid ]-387', 'font-size:13px; background:pink; color:#bf2c9f;', valid)
          if (this.list.some((el) => el.userName === this.form.userName && el.bankNoCd === this.form.bankNoCd)) {
            this.$message.error('用户重复！')
            return false
          }
          console.log('%c [ this.form ]-394', 'font-size:13px; background:pink; color:#bf2c9f;', this.form)
          const themeCode = this.form.themeCode ? this.form.themeCode.join(',') : ''
          this.confirmLoading = true
          addRoleMessage({ ...this.form, themeCode }).then((res) => {
            if (res.code === 200) {
              this.$message.success('添加成功')
              this.initList()
              this.form = {}
              this.resetForm()
            } else {
              this.confirmLoading = false
              this.$message.warning('服务器出错')
            }
          })
        } else {
          return false
        }
      })
    },
    // 删除
    removeDomain(record) {
      if (record && !this.confirmLoading) {
        this.confirmLoading = true
        const themeCode = record.themeCode ? record.themeCode.join(',') : ''
        deleteRoleMess({ ...record, themeCode }).then((res) => {
          if (res.code === 200) {
            this.initList()
            this.form = {}
            this.resetForm()
          } else {
            this.$message.warning('服务器出错')
          }
        })
      } else {
        this.form = {}
        this.resetForm()
      }
    },
    //初始化报表表记录
    initReportList2() {
      queryBankNoCdList().then((res) => {
        if (res.success) {
          this.reportsOptions = res.result.map((item, index, arr) => {
            let c = { label: item.bankname, value: item.bankNoCd, id: item.bankNoCd }
            return c
          })
        }
      })
    },
    //用户
    selectBankNoCd(value) {
      if (!(this.roleList && this.roleList[value])) {
        queryRoleList({ bankNoCd: value }).then((res) => {
          if (res.code === 200) {
            let data = this.roleList
            data[value] = res.result.map((item, index, arr) => {
              let c = { label: item.REALNAME, value: item.USERNAME, id: item.USERNAME }
              return c
            })
            this.roleList = JSON.parse(JSON.stringify(data))
          } else {
            this.$message.warning('服务器出错')
          }
        })
      }
    },
    // //初始化用户
    // initRoleList() {
    //   queryRoleList().then((res) => {
    //     if (res.success) {
    //       this.roleList = res.result.map((item, index, arr) => {
    //         let c = { label: item.ROLENAME, value: item.ID, id: item.ID }
    //         return c
    //       })
    //     }
    //   })
    // },
    //初始化主题
    initThemeList() {
      queryThemeList().then((res) => {
        if (res.success) {
          this.themeList = res.result.map((item, index, arr) => {
            let c = { label: item.name, value: item.code, id: item.code }
            return c
          })
        }
      })
    },

    // 关闭
    handleCancel() {
      this.fullScreen = false
      this.width = 1000
      this.$emit('cancel')
    },
  },
}
</script>
<style lang="less" scoped>
.myFullScreen /deep/ .ant-modal {
  top: 0;
  padding-bottom: 0;
}
.myFullScreen /deep/ .ant-modal-content {
  height: 100vh;
}
</style>